package com.guigu.health.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.guigu.health.common.MessageContstant;
import com.guigu.health.common.SendEmail;
import com.guigu.health.common.UploadFiles;
import com.guigu.health.excel.WriteExcelSetMemberDetails;
import com.guigu.health.pojo.*;
import com.guigu.health.service.*;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.commons.collections4.Get;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @ClassName:UserController
 * @Description:用户控制层
 * @Author:longtao
 * @Date:2021/3/26
 * @Version:1.0
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
    private Logger logger = Logger.getLogger(UserController.class);
    /**
     * qq邮箱验证码
     */
    String str2 = "";

    /**
     * 获取服务
     */
    @Reference
    private UserService userService;

    /**
     * 调用MemberService服务
     */
    @Reference
    private MemberService memberService;
    /**
     * 调用CheckGroupService服务
     */
    @Reference
    private CheckGroupService checkGroupService;
    /**
     * 调用setmealService服务
     */
    @Reference
    private SetmealService setmealService;
    /**
     * 调用SetMealDetailsService服务
     */
    @Reference
    private SetMealDetailsService setMealDetailsService;
    /**
     * 调用orderService服务
     */
    @Reference
    private OrderService orderService;

    /**
     * shiro验证登录注册
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/loginUser", method = RequestMethod.POST)
    public String loginUser(User user, Model model, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            model.addAttribute("flag", "succeed");

            model.addAttribute("flag2", "login");
            session.setAttribute("username", subject.getSession().getAttribute("username"));
            session.setAttribute("account", subject.getSession().getAttribute("account"));
            session.setAttribute("userID", subject.getSession().getAttribute("userID"));

            return "/page";
        } else {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
            try {
                subject.login(token);
                /**
                 * 设置model
                 */
                model.addAttribute("flag", "succeed");

                model.addAttribute("flag2", "login");
                /**
                 * 传用户名
                 */
                User user1 = userService.loginUser(user.getAccount());
                /**
                 * 获取用户名
                 */
                session.setAttribute("username", user1.getUsername());
                /**
                 * 获取到账号用来判断是否注册会员
                 */
                session.setAttribute("account", user1.getAccount());
                /**
                 * 根据id来获取修改用户
                 */
                session.setAttribute("userID", user1.getId());
                /**
                 * 成功跳转到
                 */
                return "page";
            } catch (Exception e) {
                e.printStackTrace();
                /**
                 * 失败跳转到登录页面
                 */

                model.addAttribute("flag", "fail");
                return "login";
            }
        }
    }

    /**
     * 跳转下一步,并发送验证码
     *
     * @param mailbox
     * @return
     */
    @RequestMapping(value = "/{mailbox:.+}/{mobilePhoneNumber}/{gender}/{birthday}", method = RequestMethod.GET)
    public String nextStep(@PathVariable("mailbox") String mailbox, @PathVariable String mobilePhoneNumber, @PathVariable String gender, @PathVariable String birthday, Model model) {
        /**
         * 进入此方法，验证码变为空
         */
        model.addAttribute("mailbox", mailbox);
        model.addAttribute("mobilePhoneNumber", mobilePhoneNumber);
        model.addAttribute("gender", gender);
        model.addAttribute("birthday", birthday);
        SendEmail sendEmail = new SendEmail();
        //设置要发送的邮箱
        sendEmail.setReceiveMailAccount(mailbox);
        //创建6位发验证码
        Random random = new Random();
        String str = "";
        for (int i = 0; i < 6; i++) {
            int n = random.nextInt(10);
            str += n;
        }
        str2 = str;
        sendEmail.setInfo(str);
        try {
            sendEmail.Send();
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("flag", false);
            return "register";
        }
        model.addAttribute("flag", "verification");
        return "register1";
    }

    /**
     * 注册用户并验证qq邮箱验证码
     *
     * @param
     * @param user
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String AddUser(User user, Model model) {
        if (user.getEMailVerificationCode().equals("") || user.getEMailVerificationCode() == null) {
            model.addAttribute("flag", "null");
            return "register1";
        } else if (user.getEMailVerificationCode().equals(str2)) {
            if (userService.addUser(user)) {
                model.addAttribute("flag", "succeed");
                return "login";
            } else {
                model.addAttribute("flag", "error");
                return "register1";
            }

        } else {
            model.addAttribute("flag", "incorrectness");
            return "register1";
        }
    }

    /**
     * 会员注册
     *
     * @param member
     * @param model
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addMember/", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Object addMember(@RequestBody Member member, Model model, HttpSession session) {
        Object username = session.getAttribute("username");
        /**
         * 获取当前时间
         */
        member.setRegTime(new Date());
        boolean flag = false;
        if (userService.addMember(member)) {
            flag = true;
            model.addAttribute("ADD_MEMBER", MessageContstant.ADD_MEMBER_SUCCESS);
        } else {
            model.addAttribute("ADD_MEMBER", MessageContstant.ADD_MEMBER_FAIL);
        }
        return flag;
    }

    /**
     * 跳转到会员注册页面,如果注册了直接跳转到预约页面
     *
     * @return
     */
    @RequestMapping("/goAddMember")
    public String goAddMember(String id, Model model) {
        Subject subject = SecurityUtils.getSubject();
        String account = (String) subject.getSession().getAttribute("account");
        if (account == null || "".equals(account)) {
            account = "11";
        }
        if (memberService.queryByAccount(account) == null) {
            return "WEB-INF/jsp/user/addMember";
        } else {
            /**
             * 会员ID
             */
            model.addAttribute("memberID", memberService.queryByAccount(account).getId());
            /**
             * 检查项目ID
             */
            model.addAttribute("id", id);
            return "WEB-INF/jsp/inspect/makeAnAppointment";
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    /**
     * 重定向到预约服务页面
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/appointment", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public Object appointment(String id, Model model) {
        CheckItem CheckItem = checkGroupService.queryCheckItemID(Integer.valueOf(id));
        List<CheckItem> list = new ArrayList<CheckItem>();
        list.add(CheckItem);
        return list;
    }


    /**
     * 跳转到会员注册页面,如果注册了直接跳转到预约页面
     *
     * @return
     */
    @RequestMapping("/goAddMember2")
    public String goAddMember2(String id, Model model) {
        Subject subject = SecurityUtils.getSubject();
        String account = (String) subject.getSession().getAttribute("account");
        if (memberService.queryByAccount(account) == null) {
            return "WEB-INF/jsp/user/addMember";
        } else {
            /**
             * 会员ID
             */
            model.addAttribute("memberID", memberService.queryByAccount(account).getId());
            /**
             * 超值套餐ID
             */
            model.addAttribute("id", id);
            return "WEB-INF/jsp/inspect/makeAnAppointment2";
        }

    }

    /**
     * 显示超值套餐
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/valueMeal")
    public Object valueMeal(String id) {
        SetmealExample setmealExample = new SetmealExample();
        SetmealExample.Criteria criteria = setmealExample.createCriteria();
        criteria.andIdEqualTo(Integer.valueOf(id));
        /**
         * 查询套餐
         */
        List<Setmeal> list = setmealService.selectByExample(setmealExample);
        return list;
    }

    /**
     * 显示套餐详情页面
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "packageDetails", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public Object packageDetails(String id) {
        List<SetMealDetails> list = setMealDetailsService.querySetMealID(Integer.valueOf(id));
        return list;
    }

    /**
     * 预约检查项项目
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addOrderCheckItem", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object addOrderCheckItem(@RequestBody Order order) {
        System.out.println("order = " + order);
        boolean flag = false;
        if (orderService.addOrder(order)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 预约检查套餐
     *
     * @param order
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addOrderSetMeal", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object addOrderSetMeal(@RequestBody Order order) {
        boolean flag = false;
        if (orderService.addOrder(order)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 跳转到个人主页面
     *
     * @return
     */
    @RequestMapping("/homepage")
    public String homepage() {
        return "WEB-INF/jsp/user/userPage";
    }

    /**
     * 根据用户账号查询用户详情页面,并查询是否注册会员
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userDetails", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object userDetails() {
        Subject subject = SecurityUtils.getSubject();
        String account = (String) subject.getSession().getAttribute("account");
        User user = userService.loginUser(account);
        return user;
    }

    /**
     * 根据账号查询该用户是否拥有会员
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/memberDetails", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object memberDetails() {
        Subject subject = SecurityUtils.getSubject();
        String account = (String) subject.getSession().getAttribute("account");
        Member member = memberService.queryByAccount(account);
        return member;
    }

    /**
     * 用户密码修改
     *
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword) {

        boolean flag = false;
        /**
         * 在session中获取用户账号account
         */
        String userAccount = String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("account"));
        if (userService.updatePassword(oldPassword, newPassword, userAccount)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 根据用户账号查询检查项目
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCheckItem", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object queryCheckItem() {
        String account = (String) SecurityUtils.getSubject().getSession().getAttribute("account");
        if (StringUtils.isEmpty(account)) {
            account = "111";
        }
        List<CheckItemDetails> list = checkGroupService.queryCheckItemByAccount(account);
        return list;
    }

    /**
     * 根据用户账号查找套餐列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querySetMember", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object querySetMember() {
        String account = (String) SecurityUtils.getSubject().getSession().getAttribute("account");
        if (StringUtils.isEmpty(account)) {
            account = "111";
        }
        List<SetMemberDetails> list = setmealService.querySetMealByAccount(account);
        return list;
    }

    /**
     * 修改是否到诊
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyVisit", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object modifyVisit(String id) {
        Order order = new Order();
        order.setOrderStatus("是");
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(Integer.valueOf(id));
        boolean b = orderService.updateOrder(order, example);
        return b;
    }

    /**
     * 根据id取消预约服务
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteOrder/{id}", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object deleteOrder(@PathVariable String id) {
        boolean b = orderService.deleteOrder(Integer.valueOf(id));
        return b;
    }

    /**
     * 修改日期
     *
     * @param id
     * @param date
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyDate", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object modifyDate(String id, String date) {
        Order order = new Order();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        try {
            date1 = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        order.setOrderDate(date1);

        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(Integer.valueOf(id));
        boolean b = orderService.updateOrder(order, example);
        return b;
    }


    /**
     * 将套餐数据写到excel表上,在进行下载
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/WriteExcel", produces = "text/html;charset=utf-8")
    public Boolean WriteExcel(HttpServletRequest request, HttpServletResponse response) {
        //设置响应头和客户端保存文件名
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;fileName=setMeal.xlsx");
        boolean flag = true;
        String account = String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("account"));
        List<SetMemberDetails> list = setmealService.querySetMealByAccount(account);
        /**
         * 以为对象中有些数据是数字,所以需要判断
         */
        List<SetMemberDetails2> list2 = new ArrayList<SetMemberDetails2>();
        for (SetMemberDetails details : list) {
            SetMemberDetails2 details2 = new SetMemberDetails2();
            /**
             * 判断性别
             */
            if (details.getSex() == 0) {
                details2.setSex("男女适用");
            } else if (details.getSex() == 1) {
                details2.setSex("男");
            } else if (details.getSex() == 2) {
                details2.setSex("女");
            }
            /**
             * 判断到诊状态
             */
            if ("是".equals(details.getStatus())) {
                details2.setStatus("已到诊");
            } else if ("无".equals(details.getStatus())) {
                details2.setStatus("未到诊");
            }
            /**
             * 判断注意
             */
            if (StringUtils.isEmpty(details.getAttention())) {
                details2.setAttention("暂无注意事项");
            } else {
                details2.setAttention(details.getAttention());
            }
            /**
             * 判断说明是否为空
             */
            if (StringUtils.isEmpty(details.getRemark())) {
                details2.setRemark("暂无说明");
            } else {
                details2.setRemark(details.getRemark());
            }
            details2.setAge(details.getAge());
            details2.setOrderDate(details.getOrderDate());
            details2.setName(details.getName());
            details2.setPrice(details.getPrice());
            details2.setOrderType(details.getOrderType());
            list2.add(details2);
        }
        try {
            WriteExcelSetMemberDetails.WriteSetMemberDetailsExcel(response.getOutputStream(), list2);
        } catch (Exception e) {
            flag = false;
        }

        return null;
    }

    /**
     * 将检查项目插入到excel表
     *
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/writeCheckItemExcel", produces = "text/html;charset=utf-8")
    public Boolean WriteCheckItemExcel(HttpServletResponse response, HttpServletRequest request) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;fileName=checkItem.xlsx");
        boolean flag = true;
        //设置响应头和客户端保存文件名
        List<CheckItemDetails> list = checkGroupService.queryCheckItemByAccount(String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("account")));
        List<CheckItemDetails2> list2 = new ArrayList<CheckItemDetails2>();
        for (CheckItemDetails details : list) {
            CheckItemDetails2 checkItemDetails2 = new CheckItemDetails2();
            checkItemDetails2.setAge(details.getAge());
            checkItemDetails2.setName(details.getName());
            checkItemDetails2.setPrice(details.getPrice());
            checkItemDetails2.setOrderType(details.getOrderType());
            checkItemDetails2.setOrderDate(details.getOrderDate());
            if (StringUtils.isEmpty(details.getAttention())) {
                checkItemDetails2.setAttention("暂无注意事项");
            } else {
                checkItemDetails2.setAttention(details.getAttention());
            }
            if (StringUtils.isEmpty(details.getRemark())) {
                checkItemDetails2.setRemark("暂无说明");
            } else {
                checkItemDetails2.setRemark(details.getRemark());
            }
            if (details.getSex() == 0) {
                checkItemDetails2.setSex("男女适用");
            } else if (details.getSex() == 1) {
                checkItemDetails2.setSex("男");
            } else if (details.getSex() == 2) {
                checkItemDetails2.setSex("女");
            } else {
                checkItemDetails2.setSex("阴阳人");
            }
            if (details.getType() == 1) {
                checkItemDetails2.setType("检验");
            } else if (details.getType() == 2) {
                checkItemDetails2.setType("检查");
            } else {
                checkItemDetails2.setType("未知");
            }
            if ("是".equals(details.getStatus())) {
                checkItemDetails2.setStatus("已到诊");
            } else if ("无".equals(details.getStatus())) {
                checkItemDetails2.setStatus("未到诊");
            } else {
                checkItemDetails2.setStatus("未知");
            }
            list2.add(checkItemDetails2);
        }
        try {
            /**
             * 生成excel表
             */
            /*    EasyExcel.write(response.getOutputStream(),CheckItemDetails2.class).sheet().doWrite(list2);*/
            WriteExcelSetMemberDetails.WriteCheckItemDetailsExcel(response.getOutputStream(), list2);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 用户修改
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userModification", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public Object userModification(@RequestBody User user) {
        logger.info(user);
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo((Integer) SecurityUtils.getSubject().getSession().getAttribute("userID"));
        boolean b = userService.updateUser(user, example);
        return b;
    }

    /**
     * 用户头像更换
     *
     * @param headPortrait
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userAvatarReplacement")
    public Object userAvatarReplacement(@RequestParam("file") MultipartFile headPortrait) {
        /**
         * 获取到原有图片名称,截图到后缀名
         */
        String originalFilename = headPortrait.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String a = headPortrait.getContentType();
        /**
         * 生成唯一文件名,拼接后缀名
         */
        String fileName = UUID.randomUUID() + extension;
        /**
         * 使用七牛云上传文件
         */
        try {
            UploadFiles.uploadViaByte(headPortrait.getBytes(), fileName);
            Map<String, String> map = new HashMap<String, String>();
            map.put("imgName", fileName);
            map.put("domain", UploadFiles.DOMAIN);
            /**
             * 输出url路径
             */
            String path = UploadFiles.DOMAIN + fileName;
            User user = new User();

            user.setEMailVerificationCode(path);
            logger.info("user:" + user);
            UserExample example = new UserExample();
            UserExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo((Integer) SecurityUtils.getSubject().getSession().getAttribute("userID"));
            boolean b = userService.updateUser(user, example);
            if (b) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 生成PDF文档
     *
     * @param res
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/generatePDFTable")
    public Object generatePDFTable(HttpServletResponse res) {
        Object flag = null;
        String account = String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("account"));
        MemberTwo two = memberService.queryAll(account);
        /**
         * 写到pdf表中
         */
        Document document = new Document();
        try {
            res.setCharacterEncoding("utf-8");
            res.setContentType("application/pdf");
            res.setHeader("Content-Disposition", "attachment;filename=" + two.getEmail() + ".pdf");
            PdfWriter.getInstance(document, res.getOutputStream());
            //打开文档
            document.open();
            //写内容
            //设置表格字体
            BaseFont cn = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE);
            document.add(new Paragraph("体检人:" + two.getName(), font));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            document.add(new Paragraph("性别:" + two.getSex(), font));
            document.add(new Paragraph("身份证账号:" + two.getIdCard(), font));
            document.add(new Paragraph("电话号码:" + two.getPhoneNumber(), font));
            document.add(new Paragraph("邮箱:" + two.getEmail(), font));
            String s = format.format(two.getBirthday());
            document.add(new Paragraph("生日:" + s, font));
            document.add(new Paragraph("打印PDF表日期:" + format.format(new Date()), font));
            /**
             * 设置表头
             */
            Table table = new Table(7);
            /**
             * 宽度
             */
            table.setWidth(80);
            /**
             * 边框
             */
            table.setBorder(1);
            /**
             * 水平对齐方式
             */
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            /**
             * 垂直对齐方式
             */
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
            /**
             * 设置表格属性
             */
            /**
             * 设置表格边框颜色
             */
            table.setBorderColor(new Color(0, 0, 255));
            /**
             * 设置表格与字体间的差距
             */
            table.setPadding(5);
            /**
             * 设置字体显示居中样式
             */
            /**
             * 设置表头
             */
            table.setAlignment(Element.ALIGN_CENTER);
            table.addCell(buildCell("套餐名称", font));
            table.addCell(buildCell("套餐适合性别", font));
            table.addCell(buildCell("套餐内容", font));
            table.addCell(buildCell("套餐价格", font));
            table.addCell(buildCell("是否到诊", font));
            table.addCell(buildCell("套餐注意事项", font));
            table.addCell(buildCell("套餐图片", font));
            String orderListStr = "";
            for (SetMealOrder order : two.getOrderList()) {
                /**
                 * 套餐名称
                 */
                table.addCell(buildCell(order.getName(), font));
                String str = "";
                if (order.getSex() == 0) {
                    str = "男女合适";
                } else if (order.getSex() == 1) {
                    str = "男";
                } else if (order.getSex() == 2) {
                    str = "女";
                }
                /**
                 * 套餐性别
                 */
                table.addCell(buildCell(str, font));
                /**
                 * 套餐内容
                 */
                table.addCell(buildCell(order.getRemark(), font));
                /**
                 * 套餐价格
                 */
                table.addCell(buildCell(String.valueOf(order.getPrice()), font));
                /**
                 * 预约状态
                 */
                table.addCell(buildCell(order.getOrderStatus(), font));
                /**
                 * 套餐注意事项
                 */
                table.addCell(buildCell(order.getAttention(), font));
                /**
                 * 套餐图片
                 */
                table.addCell(buildCell(order.getImg(), font));
            }
            /**
             * 添加表格
             */
            document.add(table);
            /**
             * 关闭文档
             */
            document.close();
            flag = "true";
        } catch (Exception e) {
            flag = "false";
        }
        return flag;
    }

    /**
     * 传递内容和字体样式,生成单元格
     *
     * @param content
     * @param font
     * @return
     * @throws BadElementException
     */
    private Cell buildCell(String content, Font font) throws BadElementException {
        Phrase phrase = new Phrase(content, font);
        return new Cell(phrase);
    }


    /**
     * 后台查询用户并分页
     *
     * @param name
     * @param pageNum
     * @return
     */
    @RequiresPermissions(value = {"ROLE_QUERY"})
    @ResponseBody
    @RequestMapping(value = "/queryUserAll", method = RequestMethod.GET, produces = {"application/json;charset=utf-8"})
    public Object queryUserAll(String name, String pageNum) {
        UserExample example = null;
        if (!StringUtils.isEmpty(name)) {
            example = new UserExample();
            UserExample.Criteria criteria = example.createCriteria();
            criteria.andUsernameLike("%" + name + "%");
        }else {
            example = new UserExample();
            UserExample.Criteria criteria = example.createCriteria();
        }
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }

        PageInfo<User> pageInfo = userService.queryAllUser(example, Integer.valueOf(pageNum), 2);
        return pageInfo;
    }

    /**
     * 用户资料修改
     *
     * @param user
     * @param roleIds
     * @return
     */
    @RequiresPermissions(value = {"ROLE_EDIT"})
    @ResponseBody
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
    public Object updateUser(@RequestBody User user, int[] roleIds) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(user.getId());
        userService.updateUserRoleKeyAndUser(example, user, roleIds);
        return true;
    }

    /**
     * 根据id查询出所对应的角色ID
     * @param roleID
     * @return
     */
    @RequiresPermissions(value = {"ROLE_QUERY"})
    @ResponseBody
    @RequestMapping(value = "/queryByRoleIds",method = RequestMethod.GET,produces = {"application/json;charset=utf-8"})
    public Object queryByRoleIds(String roleID){
        List<Integer> list = userService.queryByRoleIds(Integer.valueOf(roleID));
        return list;
    }


    /**
     * 显示角色ID
     * @return
     */
    @RequiresPermissions(value = {"ROLE_QUERY"})
    @ResponseBody
    @RequestMapping(value = "/queryByRle",method = RequestMethod.GET,produces = {"application/json;charset=utf-8"})
    public Object queryByRle(){
        return userService.queryAllRole();
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @RequiresPermissions(value = {"USER_DELETE"})
    @ResponseBody
    @RequestMapping(value = "/deleteUser/{id}",method = RequestMethod.GET,produces = {"application/json;charset=utf-8"})
    public Object deleteUser(@PathVariable(value = "id") String userId){
        userService.deleteUser(Integer.valueOf(userId));
        return true;
    }
}
